package com.task.filter;

import com.task.common.Cons;
import com.task.common.ReturnResult;
import com.task.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;

/**
 * @author jiafujun
 * 2020年03月24日 14:15:00
 */
@Slf4j
@ControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ReturnResult handle(HttpServletRequest req, Exception e) throws Exception {
        if (e instanceof BaseException) {
            BaseException baseException = (BaseException) e;
            return ReturnResult.build(Cons.RESULT_ERR, baseException.getMessage());
        }
        if (e instanceof AuthException) {
            AuthException authException = (AuthException) e;
            return ReturnResult.build(Cons.USER_UNAUTHORIZED, authException.getMessage());
        }

        log.error(String.format("[ERROR] : {%s},{%s}", "", e.getMessage()));
        log.error(e.getMessage(),e);
        return ReturnResult.build(Cons.RESULT_ERR,"服务器异常");
    }
}
